package io.gitee.tuo_tuo.jfinaldevassistance.test;

import com.jfinal.config.JFinalConfig;
import com.jfinal.core.JFinal;
import com.jfinal.handler.Handler;
import com.jfinal.log.Log;
import io.gitee.tuo_tuo.jfinaldevassistance.util.Reflect;
import org.junit.AfterClass;
import org.junit.Before;
import javax.servlet.ServletContext;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class JFinalTestSupport<T extends JFinalConfig> {
    protected static final Log log = Log.getLog(JFinalTestSupport.class);
	public static Handler handler;
    protected static ServletContext servletContext = new MockServletContext();
    private static boolean configStarted = false;
    private static JFinalConfig configInstance;
    private Class<? extends JFinalConfig> config;

	@SuppressWarnings("unchecked")
	public JFinalTestSupport() {
		Type genericSuperclass = getClass().getGenericSuperclass();
		if(genericSuperclass instanceof ParameterizedType == false){
			throw new RuntimeException("Your ControllerTestCase must have genericType");
		}
		config = (Class<? extends JFinalConfig>) ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
	}

	/**
	 * 启动 jfinal
	 * @throws Exception
	 */
    @Before
    public void init() throws Exception {
		if (configStarted) {
			return;
		}
		JFinal me = JFinal.me();
		configInstance = config.newInstance();
		Reflect.on(me).call("init", configInstance, servletContext);
		handler = Reflect.on(me).get("handler");
		configStarted = true;
		configInstance.afterJFinalStart();
    }

    @AfterClass
    public static void stop() {
        configInstance.beforeJFinalStop();
    }

}
